<template>
  <view class="p-4 product-detail">
    <swiper class="h-64 mb-4 rounded-lg" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
      <swiper-item v-for="(image, index) in product.images" :key="index">
        <image :src="image" mode="aspectFill" class="object-cover w-full h-full"/>
      </swiper-item>
    </swiper>
    <view class="p-4 bg-white rounded-lg shadow">
      <text class="text-xl font-bold">{{ product.name }}</text>
      <text class="block mt-2 text-2xl font-bold text-red-500">¥{{ product.price }}</text>
      <text class="block mt-4 text-gray-600">{{ product.description }}</text>
    </view>
    <view class="p-4 mt-4 bg-white rounded-lg shadow">
      <text class="mb-2 text-lg font-bold">商品详情</text>
      <rich-text :nodes="product.detailHtml"></rich-text>
    </view>
    <view class="p-4 mt-4 bg-white rounded-lg shadow">
      <text class="mb-2 text-lg font-bold">商品规格</text>
      <view v-for="(spec, index) in product.specifications" :key="index" class="mb-2">
        <text class="font-medium">{{ spec.name }}：</text>
        <text>{{ spec.value }}</text>
      </view>
    </view>
    <view class="mt-4">
      <u-button type="primary" @click="addToCart">加入购物车</u-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getProductDetail, ProductDetail } from '@/api/shop';

const product = ref<ProductDetail>({
  id: 0,
  name: '',
  price: 0,
  image: '',
  images: [],
  description: '',
  detailHtml: '',
  specifications: []
});

const addToCart = () => {
  uni.showToast({
    title: '已加入购物车',
    icon: 'success'
  });
};

onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const productId = currentPage.$page?.options?.id;

  if (productId) {
    getProductDetail(Number(productId)).then(data => {
      product.value = data;
    }).catch(error => {
      console.error('Failed to fetch product details:', error);
    });
  }
});
</script>